package com.bridge.applets.config;


import com.bridge.common.enums.RSEnum;
import com.bridge.common.exception.ServiceException;
import com.bridge.common.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class UserInterface extends AbstractSecurityInterceptor implements HandlerInterceptor {


    /**
     * Controller逻辑执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("preHandle");
        String uri = request.getServletPath();
        String pattern = "/\\d+$";
        Matcher r = Pattern.compile(pattern).matcher(uri);
        if (r.find()) {
            uri = uri.replace(r.group(), "");
        }
        log.info("uri---" + uri);
        if(uri.contains("swagger-ui")){
            return true;
        }
        //获取当前路径
        String authorization = request.getHeader("token");
        log.info("token {}",authorization);
        if (StringUtils.isEmpty(authorization)) {
            throw new ServiceException(RSEnum.LOGIN_FAIL);
        }
        String key = RedisUtil.get(authorization,String.class);
        if (StringUtils.isEmpty(key)) {
            throw new ServiceException(RSEnum.TOKEN_NOT_FOUNT);
        }
        return true;
    }

    /**
     * Controller逻辑执行完毕但是视图解析器还未进行解析之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    /**
     * Controller逻辑和视图解析器执行完毕
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }


}
